/*
 * 书籍类
 */

package dao;

import model.Book;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class BookDao {
    String book_table = "book";
    Database database = new Database();
    ArrayList<Book> arrayList = new ArrayList<>();
    Book book;

    private ArrayList<Book> getBooks(String getBook) throws SQLException {
        return getBookArrayList(getBook);
    }

    /**
     * 模糊查找图书
     *
     * @param book 书籍对象
     * @return ArrayList 类型书籍对象
     * @throws SQLException SQL相关错误
     */
    public ArrayList<Book> getBook(Book book) throws SQLException {
        String getBook = "select * from " + book_table + " where name like '%" + book.getName() + "%'";
        return getBooks(getBook);
    }

    /**
     * 单本图书的信息
     *
     * @param id 书本ID
     * @return 书本信息
     * @throws SQLException SQL错误
     */
    public ArrayList<Book> getBookInfo(int id) throws SQLException {
        String getBook = "select * from " + book_table + " where id =" + id;
        return getBooks(getBook);
    }

    public ArrayList<Book> getBookList() throws SQLException {
        String getBookList = "select * from " + book_table;
        try {
            return getBookArrayList(getBookList);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    private ArrayList<Book> getBookArrayList(String getBookList) throws SQLException {
        try (ResultSet resultSet = database.query(getBookList)) {
            while (resultSet.next()) {
                Book bookInfo = new Book();
                // TODO:这里也应该有不止ID的数据
                bookInfo.setId(resultSet.getInt("id"));
                bookInfo.setTypeId(resultSet.getInt("typeId"));
                bookInfo.setName(resultSet.getString("name"));
                bookInfo.setPrice(resultSet.getDouble("price"));
                bookInfo.setDesc(resultSet.getString("desc"));
                bookInfo.setPic(resultSet.getString("pic"));
                bookInfo.setPublish(resultSet.getString("publish"));
                bookInfo.setAuthor(resultSet.getString("author"));
                bookInfo.setStock(resultSet.getInt("stock"));
                bookInfo.setAddress(resultSet.getString("address"));
                arrayList.add(bookInfo);
            }
        }
        return arrayList;
    }

    // TODO:似乎还少了什么
}
